package cn.coder.jdbc.mapper;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import cn.coder.jdbc.core.EntityWrapper;
import cn.coder.jdbc.core.EntityWrapper.SQLType;

public final class EntityResultMapper extends BaseResultMapper<Boolean> {

	private final EntityWrapper wrapper;

	public EntityResultMapper(Object data, SQLType type) {
		this(getEntityWrapper(data, type));
	}

	private static EntityWrapper getEntityWrapper(Object data, SQLType type) {
		EntityWrapper ew = new EntityWrapper(getEntityMapping(data.getClass()));
		ew.build(data, type);
		return ew;
	}

	public EntityResultMapper(EntityWrapper wrapper) {
		super(wrapper.getJSql(), wrapper.returnGeneratedKey());
		this.wrapper = wrapper;
	}

	@Override
	public Boolean doPreparedStatement(PreparedStatement stmt) throws SQLException {
		long result;
		if (wrapper.getSqlType() == SQLType.SELECT) {
			Object firstVal = getFirstValue(stmt.executeQuery());
			result = firstVal == null ? 0 : (long) firstVal;
		} else
			result = stmt.executeUpdate();

		// 如果返回主键
		if (wrapper.returnGeneratedKey() && result > 0) {
			Object generatedKey = getFirstValue(stmt.getGeneratedKeys());
			if (generatedKey != null)
				wrapper.setGeneratedKey(generatedKey);
		}
		wrapper.clear();
		return result > 0;
	}

	private static Object getFirstValue(ResultSet result) throws SQLException {
		Object obj = null;
		while (result.next()) {
			obj = result.getObject(1);
			break;
		}
		result.close();
		return obj;
	}
}
